﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Threading.Thread;

namespace UnitTest.TaskSafetyDemo
{
    public class TaskSafety_1
    {
        public class UserMoney
        {
            public int UserId { get; set; }

            public int Money { get; set; }
        }

        public static List<UserMoney> UserMoneyList = new List<UserMoney>()
        {
            new UserMoney(){ UserId = 1, Money = 100 },
            new UserMoney(){ UserId = 2, Money = 100 }
        };

        public static void Go()
        {
            for (int i = 0; i < 20000; i++)
            {
                Random ran = new Random();
                var money = ran.Next(-5, 6);
                TransMoney(1, 2, money).Wait();
            }
        }


        public static async Task TransMoney(int userId, int toUserId, int money)
        {
            if (userId == 0 || money == 0)
                return;
            var user = UserMoneyList.Find(x => x.UserId == userId);
            if (user == null) return;
            var toUser = toUserId == 0 ? null : UserMoneyList.Find(x => x.UserId == toUserId);
            if (toUser == null)
            {
                await Task.Delay(20);
                user.Money += money;
            }
            else
            {
                if (user.Money - money < 0 || user.Money + money<0 || toUser.Money - money < 0 || toUser.Money + money < 0)
                    return;
                await Task.Delay(20);
                user.Money -= money;
                toUser.Money += money;
            }
            ShowCurrentMsg(money);
        }

        public static void ShowCurrentMsg(int money)
        {
            Console.WriteLine($"线程id：{CurrentThread.ManagedThreadId}，money:{money} user1_Money：{UserMoneyList.First(x => x.UserId == 1).Money}，user2_Money：{UserMoneyList.First(x => x.UserId == 2).Money}");
        }
    }
}
